﻿#if UNITY_EDITOR


using UnityEditor;
using UnityEngine;
using System.Reflection;

[CustomEditor(typeof(UIViewBase), true)]
public class UIViewBaseEditor : Editor
{
    private const string BindPrefix = "bind_";

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        if (GUILayout.Button("一键自动绑定UI组件"))
        {
            AutoBindUIComponents((UIViewBase)target);
        }
    }

    private void AutoBindUIComponents(UIViewBase view)
    {
        var type = view.GetType();
        var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

        foreach (var field in fields)
        {
            // 只处理带有前缀的Unity组件类型且有[SerializeField]或public
            if (!typeof(Component).IsAssignableFrom(field.FieldType)) continue;
            if (!field.Name.StartsWith(BindPrefix)) continue;
            if (!field.IsPublic && field.GetCustomAttribute<SerializeField>() == null) continue;

            // 按字段名（去掉前缀）查找子物体
            string nodeName = field.Name.Substring(BindPrefix.Length);
            var child = view.transform.Find(nodeName);
            if (child == null)
            {
                Debug.LogWarning($"未找到名为 {nodeName} 的子物体");
                continue;
            }

            var comp = child.GetComponent(field.FieldType);
            if (comp == null)
            {
                Debug.LogWarning($"子物体 {nodeName} 上未找到组件 {field.FieldType.Name}");
                continue;
            }

            field.SetValue(view, comp);
            EditorUtility.SetDirty(view);
        }

        Debug.Log("UI组件自动绑定完成（仅限带前缀字段）");
    }
}
#endif